//
//  DataBaseManager.m
//  News
//
//  Created by sqx on 15/7/21.
//  Copyright (c) 2015年 蓝欧科技. All rights reserved.
//

#import "DataBaseManager.h"

@implementation DataBaseManager
//因为对于一个程序一个数据库足以  所以只需要一个对象
static sqlite3 *db = nil;
+ (sqlite3 *)openDataBase
{
    //    @synchronized
    if (db) {
        return db;
    }
    
    //获取Caches文件路径
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    //拼接数据库文件路径
    NSString *dbPath = [cachesPath stringByAppendingString:@"/DB.sqlite"];
    NSLog(@"%@",cachesPath);
    
    //打开数据库
    //根据给定文件路经打开数据库 如果数据库文件不存在 就会先创建一个
    int result = sqlite3_open([dbPath UTF8String], &db);
    if (result == SQLITE_OK) {
        NSLog(@"成功打开数据库");
        
        //sql语句 blob 2进制 保存
        //已订阅表
        NSString *sqlStr = @"CREATE TABLE Subscibe(subscibeID integer primary key ,ItemName text,strURL text,strKey text) ";
        //执行sql语句
        sqlite3_exec(db, [sqlStr UTF8String], NULL, NULL, NULL);
        //未订阅表
        NSString *sqlStr1 = @"CREATE TABLE NotSubscibe(subscibeID integer primary key ,ItemName text,strURL text,strKey text) ";
        //执行sql语句
        sqlite3_exec(db, [sqlStr1 UTF8String], NULL, NULL, NULL);
        //设置表
        NSString *sqlStr2 = @"CREATE TABLE SetTable(setID integer primary key ,nightMode integer ,textFont integer,DownLoadWIFI integer) ";
        //执行sql语句
        sqlite3_exec(db, [sqlStr2 UTF8String], NULL, NULL, NULL);
        //用户表
        NSString *sqlStr3 = @"create table User(user_id integer primary key not null,userName text not null,password text not null,surePassword text not null,phoneNumber text not null)";
        //执行sql语句
        sqlite3_exec(db, [sqlStr3 UTF8String], NULL, NULL, NULL);
        NSString*sqlStr4=@"CREATE TABLE SAVE(saveID integer primary key ,title text ,source text,ptime text,jsstring text)";
        sqlite3_exec(db, [sqlStr4 UTF8String], NULL, NULL, NULL);
        
        sqlite3_exec(db, [sqlStr3 UTF8String], NULL, NULL, NULL);
        NSString*sqlStr5=@"CREATE TABLE NewsData(newsID integer primary key ,title text ,newsdata blob)";
        sqlite3_exec(db, [sqlStr5 UTF8String], NULL, NULL, NULL);
        
    }
    return db;
}

+ (void)closeDataBase
{
    int result = sqlite3_close(db);
    if (result == SQLITE_OK) {
        NSLog(@"关闭数据库");
        db = nil;
    }
}

@end
